// game.js
let ROWS, COLS, MINES;
let grid = [];
let revealed = new Set();
let flagged = new Set();
let gameOver = false;
let flagMode = false; // 标记模式的开关
let startTime = null;
let timerInterval = null;

// 添加一个变量来追踪已标记数量
let flaggedCount = 0;

// 长按检测变量
let touchTimeout = null;
const LONG_PRESS_TIME = 500; // 长按时间阈值（毫秒）

// 更新状态显示函数
function updateStatus() {
    document.getElementById('mine-count').textContent = MINES;
    document.getElementById('flag-count').textContent = flaggedCount;
    document.getElementById('timer').textContent = startTime ? Math.floor((Date.now() - startTime) / 1000) : 0;
}

function initGame(rows, cols, mines) {
    ROWS = rows;
    COLS = cols;
    MINES = mines;
    flaggedCount = 0; // 重置标记计数
    const gridElement = document.getElementById('grid');
    gridElement.innerHTML = '';

    // 初始化网格
    for (let i = 0; i < ROWS; i++) {
        grid[i] = new Array(COLS).fill(0);
        for (let j = 0; j < COLS; j++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            cell.dataset.row = i;
            cell.dataset.col = j;
            cell.addEventListener('click', handleClick); // 统一使用点击事件
            cell.addEventListener('contextmenu', handleRightClick); // 添加右键事件
            cell.addEventListener('touchstart', handleTouchStart); // 添加触摸开始事件
            cell.addEventListener('touchend', handleTouchEnd); // 添加触摸结束事件
            gridElement.appendChild(cell);
        }
    }

    // 放置雷
    let minesPlaced = 0;
    while (minesPlaced < MINES) {
        const row = Math.floor(Math.random() * ROWS);
        const col = Math.floor(Math.random() * COLS);
        if (grid[row][col] !== -1) {
            grid[row][col] = -1;
            minesPlaced++;
        }
    }

    // 计算数字
    for (let i = 0; i < ROWS; i++) {
        for (let j = 0; j < COLS; j++) {
            if (grid[i][j] === -1) continue;
            let count = 0;
            for (let di = -1; di <= 1; di++) {
                for (let dj = -1; dj <= 1; dj++) {
                    const ni = i + di;
                    const nj = j + dj;
                    if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && grid[ni][nj] === -1) {
                        count++;
                    }
                }
            }
            grid[i][j] = count;
        }
    }

    updateStatus();
}

function handleClick(event) {
    if (gameOver) return;
    if (!startTime) startTimer();

    const row = parseInt(event.target.dataset.row);
    const col = parseInt(event.target.dataset.col);

    if (flagMode) {
        toggleFlag(row, col);
    } else {
        reveal(row, col);
    }

    updateStatus();
    checkWin();
}

// 右键事件处理
function handleRightClick(event) {
    event.preventDefault(); // 阻止默认的右键菜单
    if (gameOver) return;
    if (!startTime) startTimer();

    const row = parseInt(event.target.dataset.row);
    const col = parseInt(event.target.dataset.col);
    toggleFlag(row, col);
    updateStatus();
}

// 长按开始事件
function handleTouchStart(event) {
    if (gameOver) return;
    if (!startTime) startTimer();

    const row = parseInt(event.target.dataset.row);
    const col = parseInt(event.target.dataset.col);

    // 设置长按超时
    touchTimeout = setTimeout(() => {
        toggleFlag(row, col); // 长按触发标记
        updateStatus();
    }, LONG_PRESS_TIME);
}

// 长按结束事件
function handleTouchEnd(event) {
    clearTimeout(touchTimeout); // 清除长按超时
}

function toggleFlag(row, col) {
    const key = `${row},${col}`;
    const cellElement = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);

    if (revealed.has(key)) return; // 已揭示的单元格不能标记

    if (flagged.has(key)) {
        flagged.delete(key);
        flaggedCount--;
        cellElement.textContent = '';
    } else {
        flagged.add(key);
        flaggedCount++;
        cellElement.textContent = '🚩';
    }

    updateStatus();
}

function reveal(row, col) {
    const key = `${row},${col}`;
    if (revealed.has(key) || flagged.has(key)) return;

    const cellElement = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
    revealed.add(key);
    cellElement.classList.add('revealed');

    if (grid[row][col] === -1) {
        gameOver = true;
        cellElement.classList.add('mine');
        cellElement.textContent = '💣';
        revealAllMines();
        stopTimer();
        alert('游戏结束!');
        return;
    }

    if (grid[row][col] === 0) {
        for (let di = -1; di <= 1; di++) {
            for (let dj = -1; dj <= 1; dj++) {
                const ni = row + di;
                const nj = col + dj;
                if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS) {
                    reveal(ni, nj);
                }
            }
        }
    } else {
        cellElement.textContent = grid[row][col];
    }
}

function revealAllMines() {
    for (let i = 0; i < ROWS; i++) {
        for (let j = 0; j < COLS; j++) {
            if (grid[i][j] === -1) {
                const cellElement = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
                cellElement.classList.add('revealed', 'mine');
                cellElement.textContent = '💣';
            }
        }
    }
}

function checkWin() {
    const totalCells = ROWS * COLS;
    const revealedCount = revealed.size;
    const remainingCells = totalCells - revealedCount;

    if (remainingCells === MINES) {
        gameOver = true;
        stopTimer();
        alert('恭喜你赢了!');
    }
}

function toggleFlagMode() {
    flagMode = !flagMode;
    document.getElementById('flag-toggle').classList.toggle('flag-mode');
    updateStatus();
}

function startTimer() {
    startTime = Date.now();
    timerInterval = setInterval(() => {
        updateStatus();
    }, 1000);
}

function stopTimer() {
    clearInterval(timerInterval);
}

function resetGame() {
    revealed.clear();
    flagged.clear();
    gameOver = false;
    flagMode = false;
    document.getElementById('flag-toggle').classList.remove('flag-mode');
    stopTimer();
    startTime = null;
    initGame(ROWS, COLS, MINES);
    updateStatus();
}